<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/17
 * Time: 21:02
 */

namespace app\api\until;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
class Token
{
    public function makeToken($uid)
    {
        $time = time();


        $signer = new Sha256();

        $token = (new Builder())->setIssuer(config('web_site_domain')) // Configures the issuer (iss claim)
        ->setAudience(config('web_site_domain')) // Configures the audience (aud claim)
        ->setId(config('token_id'), true) // Configures the id (jti claim), replicating as a header item
        ->setIssuedAt($time) // Configures the time that the token was issue (iat claim)
        ->setNotBefore($time + config('token_expiry_time')) // Configures the time that the token can be used (nbf claim)
        ->setExpiration($time + config('token_expiration_time')) // Configures the expiration time of the token (exp claim)
        ->set('uid', $uid) // Configures a new claim, called "uid"
        ->sign($signer, config('web_token_secret')) // creates a signature using "testing" as key
        ->getToken(); // Retrieves the generated token

        return $token->__toString();
    }

    public function decodeToken($token_str)
    {


        $signer = new Sha256();
        $token = (new Parser())->parse((string)$token_str);
        if (!$token->verify($signer, config('web_token_secret'))) {
            return false; //签名不正确
        }
        $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
        $data->setIssuer(config('web_site_domain'));
        $data->setAudience(config('web_site_domain'));
        $data->setId(config('token_id'));
        $res = $token->validate($data);
        if($res !== true){
            return $res;
        }else{
            $arr = [];
            $arr['uid'] = $token->getClaim('uid');
            $arr['info'] = $token->getClaims();
            return $arr['uid'];
        }
    }

    public function validateTokenIsExpired($token_str)
    {
        $token = (new Parser())->parse((string)$token_str);
        return $token->isExpired();
    }
}